using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using ODX.Core;
using ODX.LazyUnitTester;

namespace Paging
{
    [Table]
    public abstract class OdxOrder : Entity
    {
        public abstract decimal Price{ get; set; }
        public abstract DateTime OrderDate { get; set; }
    }

    [TestFixture]
    public class C11_Paging
    {
        [TestBody]
        static void Main()
        {
            const string filename = "pager.xml";
            if (File.Exists(filename))
                File.Delete(filename);

            Session writer = new Session(new XmlDataProvider(filename));
            writer.RegisterAssembly(Assembly.GetExecutingAssembly());
            writer.Prepare();

            Random r = new Random(1123123);
            for ( int i = 0; i < 100; i++ )
            {
                OdxOrder m = writer.Create<OdxOrder>();
                m.Price = i/3;

                // Let some values be null
                if ( r.Next(100) > 5 )
                    m.OrderDate = new DateTime(2007, 01, 01) + TimeSpan.FromDays(r.Next(90));
            }

            writer.Save();

            Session reader = writer.Clone();

            Pager<OdxOrder> p = new Pager<OdxOrder>(reader, "OrderDate >= ? OR OrderDate IS NULL", "OrderDate DESC, Price", 12, new DateTime(2007,02,01));

            WriteOrders(p.First);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Next);
            WriteOrders(p.Last);
            WriteOrders(p.Prev);

            LUT.WriteLine("-----------------------------");

            //foreach ( OdxOrder order in p)
            //    WriteOrder(order);

        }

        private static void WriteOrder(OdxOrder order)
        {
            LUT.WriteLine("{0}\t{1}", order.Price, order.OrderDate);            
        }

        private static void WriteOrders(ICollection<OdxOrder> orders)
        {
            LUT.WriteLine("-");
            foreach (OdxOrder order in orders)
                WriteOrder(order);
        }

        [Test]
        public void Test()
        {
            LUT.Execute(Main);
        }
    }
}
